package jmine.tec.test.utils.thread;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.beans.factory.access.SingletonBeanFactoryLocator;

/**
 * Suite that is aware of the bean factory and is multi thread.
 * 
 * @author jrenaut
 */
public class BeanFactoryAwareMultiThreadTestSuite extends MultiThreadTestSuite {

    private static final String DEFAULT_REF_FACTORY = "classpath:beanRefFactory.xml";

    private final String factoryKey;

    private String beanRefFactory;

    private BeanFactoryLocator locator;

    private BeanFactoryReference beanFactoryReference;

    /**
     * C'tor
     * 
     * @param factoryKey the factoryKey to use
     */
    public BeanFactoryAwareMultiThreadTestSuite(final String factoryKey) {
        super();
        this.factoryKey = factoryKey;
        this.beanRefFactory = DEFAULT_REF_FACTORY;
    }

    /**
     * C'tor
     * 
     * @param testName the test name
     * @param factoryKey the factory key
     */
    public BeanFactoryAwareMultiThreadTestSuite(final String testName, final String factoryKey) {
        super(testName);
        this.factoryKey = factoryKey;
        this.beanRefFactory = DEFAULT_REF_FACTORY;
    }

    /**
     * C'tor
     * 
     * @param beanRefFactory bean ref file
     * @param testName test name
     * @param factoryKey factory key in ref file
     */
    public BeanFactoryAwareMultiThreadTestSuite(final String beanRefFactory, final String testName, final String factoryKey) {
        this(testName, factoryKey);
        this.beanRefFactory = beanRefFactory;
    }

    /**
     * Raise the bean favtory before the tests are run.
     */
    @Override
    protected void beforeTests() {
        super.beforeTests();

        this.locator = SingletonBeanFactoryLocator.getInstance(this.beanRefFactory);
        if (this.locator != null) {
            this.beanFactoryReference = this.locator.useBeanFactory(this.factoryKey);
        }
    }

    /**
     * Destroys the bean factory after all tests are run.
     */
    @Override
    protected void afterTests() {
        if (this.beanFactoryReference != null) {
            this.beanFactoryReference.release();
        }
        super.afterTests();
    }

}
